<?php
namespace app\beautiful\controller\admin\mall;
use app\BaseController;
use app\common\logic\DataLogic;
use app\beautiful\model\mall\FlashSaleGoodsModel;
use app\beautiful\model\mall\FlashSaleGoodsSkuModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;

class FlashSale extends BaseController{
    protected $name='秒杀商品';

    public function index()
    {
        $name=$this->request->param('name');
        $bg_take_count=$this->request->param('bg_take_count/d');
        $end_take_count=$this->request->param('end_take_count/d');
        $status=$this->request->param('status/d',1);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];
        $goods_where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];
        if(!empty($name)) $goods_where[]=['name','=',$name];
        $goods_ids=GoodsModel::where($goods_where)->column('goods_id') ?? [];
        $where[]=['goods_id','in',$goods_ids];

        if(!empty($bg_take_count)){
            if(!empty($end_take_count)){
                $where[]=['take_count','between',[$bg_take_count,$end_take_count]];
            }else{
                $where[]=['take_count','>=',$bg_take_count];
            }
        }else{
            if(!empty($end_take_count)){
                $where[]=['take_count','<=',$end_take_count];
            }
        }

        if(!empty($status)) $where[]=['status','=',$status];

        $flash_sale_goods_model= new FlashSaleGoodsModel();
        $flash_sale_goods_model = $flash_sale_goods_model->with(['goods']);
        $order=['update_time'=>'desc','flash_sale_goods_id'=>'desc'];
        $field="*";
        $append=['add_time_format'];
        $return = DataLogic::getDataList($flash_sale_goods_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function show()
    {

        $flash_sale_goods_id=$this->request->param('flash_sale_goods_id/d',0);
        if($flash_sale_goods_id==0) return $this->success([]);

        if(null === $flash_sale_goods= FlashSaleGoodsModel::find($flash_sale_goods_id)) return $this->error($this->name.'不存在');
        if($flash_sale_goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($flash_sale_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        $sku=FlashSaleGoodsSkuModel::where([['flash_sale_goods_id','=',$flash_sale_goods_id],['is_delete','=',0]])->select()->toArray() ?? [];
        $flash_sale_goods->append(['flash_sale_time']);
        $detail=[
            'goods'=>$flash_sale_goods->goods,
            'flash_sale_price'=>$flash_sale_goods->flash_sale_price,
            'flash_sale_time'=>$flash_sale_goods->flash_sale_time,
            'quota'=>$flash_sale_goods->quota,
            'fictitious_take_count'=>$flash_sale_goods->fictitious_take_count,
            'is_tui'=>$flash_sale_goods->is_tui,
            'is_have_sku'=>$flash_sale_goods->is_have_sku,
            'sku'=>$sku,
            'is_open_yu'=>$flash_sale_goods->is_open_yu,
            'flash_sale_info'=>$flash_sale_goods->flash_sale_info,
        ];
        return $this->success(['detail'=>$detail]);
    }


    public function save()
    {
        $flash_sale_goods_id=$this->request->param('flash_sale_goods_id/d',0);
        $goods_id = $this->request->param('goods_id/d',0);
        $flash_sale_price = $this->request->param('flash_sale_price/f',0);
        $flash_sale_time=$this->request->param('flash_sale_time/a',[]);
        $quota=$this->request->param('quota/d',0);
        $fictitious_take_count=$this->request->param('fictitious_take_count/d',0);
        $is_tui=$this->request->param('is_tui/d',0);
        $is_have_sku=$this->request->param('is_have_sku/d',0);
        $sku=$this->request->param('sku','','security_json_or_array');
        $flash_sale_info=$this->request->param('flash_sale_info');

        //判断传来的参数
        if(null === $goods= GoodsModel::find($goods_id)) return $this->error('商品不存在');
        if($goods->is_delete!=0) return $this->error('商品不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('商品不存在');
        if(empty($flash_sale_price) || $flash_sale_price<=0) return $this->error('请输入秒杀价，且不能小于0');
        if($flash_sale_price > $goods->original_price) return $this->error('秒杀价不能大于商品原价');
        if(empty($flash_sale_time) ||count($flash_sale_time) != 2) return $this->error('请选择秒杀时间');
        $start_time=$flash_sale_time[0]; $end_time=$flash_sale_time[1];
        if(false === $start_time_unix = strtotime($start_time)) return $this->error('请选择正确的秒杀开始时间');
        if(false === $end_time_unix = strtotime($end_time)) return $this->error('请选择正确的秒杀结束时间');
        if($start_time<date("Y-m-d",$this->request->time())) return $this->error('秒杀开始时间不能小于当前时间');
        if($end_time_unix<$start_time_unix) return $this->error('秒杀开始时间不能大于结束时间');
        if((empty($quota) || $quota<=0) && $is_have_sku==0) return $this->error('请输入配额，且不能小于0');
        if(empty($fictitious_take_count) || $fictitious_take_count <=0) return $this->error('请输入需要展示的销量');
        if(!in_array($is_tui,[0,1])) return $this->error('未设置是否推荐');
        if(!in_array($is_have_sku,[0,1])) return $this->error('未设置是否有规格');
        if($is_have_sku==1){
            if(empty($sku) || !is_array($sku)) return $this->error('请填写规格');
            $quota=0;
            foreach ($sku as $k => $v){
                if(empty($v['name'])) return $this->error('请输入规格第'.($k+1).'行的名称');
                if(empty($v['original_price']) || $v['original_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的原价，且不能小于0');
                if(empty($v['flash_sale_price']) || $v['flash_sale_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的秒杀价，且不能小于0');
                if($v['flash_sale_price'] > $v['original_price']) return $this->error('规格第'.($k+1).'行的秒杀价不能大于原价');
                if(empty($v['quota']) || $v['quota'] <= 0) return $this->error('请输入规格第'.($k+1).'行的配额，且不能小于0');
                $quota=$quota+$v['quota'];
            }
        }
        if(empty($flash_sale_info)) return $this->error('请输入秒杀说明');

        //操作
        if($flash_sale_goods_id != 0){
            if(null === $flash_sale_goods= FlashSaleGoodsModel::find($flash_sale_goods_id)) return $this->error($this->name.'不存在');
            if($flash_sale_goods->is_delete!=0) return $this->error($this->name.'不存在');
            if($flash_sale_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
            if($flash_sale_goods->goods_id != $goods_id){
                if(null !== FlashSaleGoodsModel::where([
                        ['shop_id','=',$this->request->shopId],
                        ['goods_id','=',$goods_id],
                        ['status','=',1],
                        ['is_delete','=',0],
                        ['end_time','>=',date("Y-m-d",$this->request->time())]
                    ])->find()){
                    return $this->error('这个商品已经参与秒杀中');
                }
            }
        }else{
            $flash_sale_goods = new FlashSaleGoodsModel();
            $flash_sale_goods->shop_id = $this->request->shopId;
            if(null !== FlashSaleGoodsModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['goods_id','=',$goods_id],
                    ['status','=',1],
                    ['is_delete','=',0],
                    ['end_time','>=',date("Y-m-d",$this->request->time())]
                ])->find()){
                return $this->error('这个商品已经参与秒杀中');
            }
        }
        $flash_sale_goods->goods_id =$goods_id;
        $flash_sale_goods->flash_sale_price =$flash_sale_price;
        $flash_sale_goods->start_time =$start_time;
        $flash_sale_goods->end_time =$end_time;
        $flash_sale_goods->quota =$quota;
        $flash_sale_goods->fictitious_take_count =$fictitious_take_count;
        $flash_sale_goods->is_tui =$is_tui;
        $flash_sale_goods->is_have_sku =$is_have_sku;
        $flash_sale_goods->flash_sale_info =$flash_sale_info;
        $flash_sale_goods->status=1;
        $flash_sale_goods->update_time=$this->request->time();
        $flash_sale_goods->save();

        //规格操作
        if($is_have_sku==1){
            $old_flash_sale_goods_sku=FlashSaleGoodsSkuModel::where([
                ['shop_id','=',$this->request->shopId],
                ['flash_sale_goods_id','=',$flash_sale_goods->flash_sale_goods_id],
                ['is_delete','=',0]
            ])->select()->toArray();
            $update_flash_sale_goods_ids=array_column($sku,'flash_sale_goods_id') ?? []; $delete_flash_sale_goods_sku=[];
            $old_flash_sale_goods_sku_ids=array_column($old_flash_sale_goods_sku,'flash_sale_goods_id') ?? [];
            foreach ($old_flash_sale_goods_sku as $k => $v){
                if(!in_array($v['flash_sale_goods_id'],$update_flash_sale_goods_ids)){
                    $v['is_delete']=1;
                    $delete_flash_sale_goods_sku[]=$v;
                }
            }

            $sku_ids=GoodsSkuModel::where([
                ['shop_id','=',$this->request->shopId],
                ['goods_id','=',$goods_id],
                ['is_delete','=',0]
            ])->column('sku_id') ?? [];
            foreach ($sku as $k => $v){
                $sku[$k]['shop_id']=$this->request->shopId;
                $sku[$k]['flash_sale_goods_id']=$flash_sale_goods->flash_sale_goods_id;
                if(isset($v['flash_sale_goods_sku_id'])){
                    if(!in_array($v['flash_sale_goods_sku_id'],$old_flash_sale_goods_sku_ids)) unset($sku[$k]);
                }
                if(isset($v['sku_id'])){
                    if(!in_array($v['sku_id'],$sku_ids)) unset($sku[$k]);
                }
            }
            $new_sku=array_merge($sku,$delete_flash_sale_goods_sku);
            //更新
            $flash_sale_goods_sku_model= new FlashSaleGoodsSkuModel();
            $flash_sale_goods_sku_model->saveAll($new_sku);
        }
        return $this->success('保存成功');
    }

    public function undercarriage()
    {
        $flash_sale_goods_id=$this->request->param('flash_sale_goods_id/d',0);

        if(null === $flash_sale_goods= FlashSaleGoodsModel::find($flash_sale_goods_id)) return $this->error($this->name.'不存在');
        if($flash_sale_goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($flash_sale_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($flash_sale_goods->status == -1) return $this->error($this->name.'已下架');
        //其他判断后面补充

        $flash_sale_goods->status=-1;
        $flash_sale_goods->save();
        return $this->success('下架成功');
    }

    public function grounding()
    {
        $flash_sale_goods_id=$this->request->param('flash_sale_goods_id/d',0);

        if(null === $flash_sale_goods= FlashSaleGoodsModel::find($flash_sale_goods_id)) return $this->error($this->name.'不存在');
        if($flash_sale_goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($flash_sale_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($flash_sale_goods->status == 1) return $this->error($this->name.'已上架');
        //其他判断后面补充

        $flash_sale_goods->status=1;
        $flash_sale_goods->update_time=$this->request->time();
        $flash_sale_goods->save();
        return $this->success('下架成功');
    }
}